package com.kzj.common.interceptor;



import com.kzj.common.constant.GlobalConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;

@Slf4j
@Component
public class MyHttpServletRequestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{
            log.info("request信息如下：");
            StringBuffer url = request.getRequestURL();
            String queryString = request.getQueryString();
            String method = request.getMethod();
            String remoteAddr = request.getRemoteAddr();
            String json= StreamUtils.copyToString(request.getInputStream(), Charset.forName(GlobalConstant.CHARSET_UTF_8));
            log.info("\n" +
                    "+------------+--------------------------------------------------------------------------------+\n" +
                    String.format("|%-10s  |%-80s|\n","method",method)+
                    String.format("|%-10s  |%-80s|\n","url",url)+
                    String.format("|%-10s  |%-80s|\n","params",queryString)+
                    String.format("|%-10s  |%-80s|\n","ip",remoteAddr)+
                    String.format("|%-10s  |%-80s|\n","json",json)+
                    "+------------+--------------------------------------------------------------------------------+\n"
            );
            return true;
        }
        catch(Exception e)
        {
            response.setStatus(444);
            response.getWriter().write("nu know");
            return true;
        }

    }
}
